package com.agv.web.rpt;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.agv.core.exception.AgvException;
import com.agv.core.objectDomain.DataModel;
import com.agv.core.services.rpt.IRptService;

public class RptDispatchAction extends DispatchAction {

	private IRptService rptService;

	public ActionForward getReport(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			ServletOutputStream out = response.getOutputStream();
			JSONObject objeto = new JSONObject();
			JSONArray array = new JSONArray();

			String nbReport = request.getParameter("tpReport");

			DataModel dataModel = rptService.getDataModel(nbReport);
			List<Map<String, String>> list = dataModel.getData();

			request.getSession().setAttribute("reportList", list);
			request.getSession().setAttribute("reportDataModel", dataModel);

			String start = request.getParameter("start");
			int inicio = (start == null) ? 0 : Integer.parseInt(start);

			for (Map<String, String> element : list) {

				Set<String> set = element.keySet();

				JSONObject jsonObject = new JSONObject();
				for (String fieldName : set) {
					jsonObject.put(fieldName, element.get(fieldName));
				}

				array.put(jsonObject);
			}

			JSONObject metaData = getFields(dataModel);

			objeto.put("total", array.length());
			objeto.put("rows", array);
			objeto.put("metaData", metaData);

			out = response.getOutputStream();
			out.println(objeto.toString());
			return null;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * @param dataModel
	 * @return
	 * @throws JSONException
	 */
	public JSONObject getFields(DataModel dataModel) throws JSONException {

		JSONObject fields = new JSONObject();
		JSONObject finalfield = new JSONObject();
		JSONArray a = new JSONArray();

		for (String dataIndex : dataModel.getNbParams().split(",")) {
			fields = new JSONObject();
			fields.put("name", dataIndex);
			a.put(fields);
		}

		finalfield.put("fields", a);
		finalfield.put("root", "rows");
		finalfield.put("totalProperty", "total");
		return finalfield;
	}

	public void setRptService(IRptService rptService) {
		this.rptService = rptService;
	}

	public String getReportConf(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			ServletOutputStream out = response.getOutputStream();
			String nbReport = request.getParameter("tpReport");
			DataModel dataModel = rptService.getDataModel(nbReport);

			JSONObject json = new JSONObject();
			JSONArray data = new JSONArray();
			JSONArray formArray = new JSONArray();
			JSONObject column2 = new JSONObject();
			json.put("titulo", dataModel.getRptTitle());
			json.put("campo", "");
			JSONObject column = new JSONObject();

			int counter = 0;
			String[] headers = dataModel.getNbHeaders().split(",");
			for (String dataIndex : dataModel.getNbParams().split(",")) {
				column = new JSONObject();
				column.put("sortable", "true");
				column.put("header", headers[counter++]);
				column.put("dataIndex", dataIndex);
				column.put("align", "left");
				data.put(column);
			}

			getFields(dataModel);

			column2.put("form", formArray);
			column2.put("rows", data);
			out = response.getOutputStream();
			out.println(column2.toString());
			return null;
		} catch (Exception e) {
			log.error(e);
			throw new AgvException(e);
		}
	}

	@SuppressWarnings("unchecked")
	public ActionForward getTxtReport(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		List<Map<String, String>> list = (List<Map<String, String>>) request
				.getSession().getAttribute("reportList");

		FileWriter ryt = new FileWriter("/test.txt");
		BufferedWriter outt =new BufferedWriter(ryt);
		outt.write("Hello, ");
		outt.write("\r\nThis the simple txt file that you created!");
		outt.close();
		
		// for (Map<String, String> element : list) {
		// String line = "";
		// Set<String> set = element.keySet();
		// for (String fieldName : set) {
		// line += element.get(fieldName);
		// }
		//
		// }
		//
		// DataModel dataModel = (DataModel) request.getSession().getAttribute(
		// "reportDataModel");

		return null;
	}
}
